import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { TalkEntity } from './entities/talk.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RoomEntity } from './entities/room.entity';
@WebSocketGateway(9892, { cors: true })
export class TalkGateway {
  constructor(
    @InjectRepository(TalkEntity)
    private readonly talkRepository: Repository<TalkEntity>,

    @InjectRepository(RoomEntity)
    private readonly roomRepository: Repository<RoomEntity>,
  ) {}
  @WebSocketServer() msgServer: Server;
  @SubscribeMessage('message')
  async handleMessage(client: Socket, data: sendData) {
    // 根据roomName在数据库存入信息
    // 根据roomName查询room的id
    const room = await this.roomRepository.findOne({
      where: { roomName: data.roomName },
    });
    const messageData = {
      roomId: room.id,
      roomName: data.roomName,
      msgData: JSON.stringify(data),
    };
    this.addMsg(messageData as TalkEntity);
    //向除自己以外的人广播
    client.broadcast.emit('message', data);
  }

  // 向数据库存入信息
  async addMsg(data: TalkEntity) {
    return this.talkRepository.save(data);
  }

  @WebSocketServer() joinServer: Server;
  @SubscribeMessage('join')
  async handleJoin(client: Socket, data: any) {
    // 根据房间名查ID
    const room = await this.roomRepository.findOne({
      where: { roomName: data.roomName },
    });
    const onlineUsers = !!room.onlineUsers ? JSON.parse(room.onlineUsers) : [];
    // 根据userId去重
    const index = onlineUsers.findIndex((item) => item.userId === data.userId);
    if (index > -1) {
      onlineUsers.splice(index, 1);
    }
    // 存入在线用户
    onlineUsers.push(data);
    room.onlineUsers = JSON.stringify(onlineUsers);
    await this.roomRepository.update(room.id, room);
    //向除自己以外的人广播
    console.log('join', data);
    const res = {
      roomName: data.roomName,
      onlineUsers,
    };
    client.broadcast.emit('join', res);
  }

  @WebSocketServer() leaveServer: Server;
  @SubscribeMessage('leave')
  async handleLeave(client: Socket, data: any) {
    // 根据房间名查ID
    const room = await this.roomRepository.findOne({
      where: { roomName: data.roomName },
    });
    let onlineUsers = !!room.onlineUsers ? JSON.parse(room.onlineUsers) : [];
    onlineUsers = onlineUsers.filter(
      (user: any) => user.userId !== data.userId,
    );
    room.onlineUsers = JSON.stringify(onlineUsers);
    await this.roomRepository.update(room.id, room);
    //向除自己以外的人广播
    console.log('leave', data);
    const res = {
      roomName: data.roomName,
      onlineUsers,
    };
    client.broadcast.emit('leave', res);
  }
}

// 前端发过来的数据格式
interface sendData {
  userId: number;
  msg: string;
  user: string;
  roomName: string;
}
